/**
 * 20220118：created by jordia
 */
import {InstancedMesh, Matrix4} from "three";
import VirtualPlane from "./virtual-plane";

const _mesh=new VirtualPlane();
const _instanceLocalMatrix=new Matrix4();
const _instanceWorldMatrix=new Matrix4();
const _instanceIntersects=[];

/**
 * 实例渲染虚拟平面
 * @param geometry {BufferGeometry} 虚拟平面几何体
 * @param material {ShaderMaterial} 虚拟平面材质
 * @param count {number} 最大渲染实例数量
 */
export default class VirtualPlanes extends InstancedMesh{
    constructor(geometry,material,count){
        super(geometry,material,count);
    }

    raycast( raycaster, intersects ) {
        const matrixWorld = this.matrixWorld;
        const raycastTimes = this.count;
        _mesh.geometry = this.geometry;
        _mesh.material = this.material;
        if ( _mesh.material === undefined ) return;
        for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
            this.getMatrixAt( instanceId, _instanceLocalMatrix );
            _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
            _mesh.matrixWorld = _instanceWorldMatrix;
            _mesh.raycast( raycaster, _instanceIntersects );
            for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
                const intersect = _instanceIntersects[ i ];
                intersect.instanceId = instanceId;
                intersect.object = this;
                intersects.push( intersect );
            }
            _instanceIntersects.length = 0;

        }

    }

}